package com.putable.pqueue;
/**
 * 
 * @author Todd
 *
 *
 * Does the double and copy array work for the PQueue
 */

public abstract class DoubleAndCopy implements PQueue {
	private int oldArrIndex;
	private PQAble[] arr = new PQAble[4];
	private PQAble[] oldArr;
	
	/**
	 * If the array has gotten too big double it and create a copy
	 * @param index The index of the last item in the array
	 */
	private void doubleAndCopy(int index){
		if(index == arr.length - 1){
			oldArr = arr;
			arr = new PQAble[arr.length * 2];
			oldArrIndex = oldArr.length;
			copyFromOld();
		}
	}
	/**
	 * Copies one item from the old array and puts it in the new one
	 */
	private void copyFromOld(){
		if(oldArrIndex <= 0) return;
		oldArrIndex --;
		arr[oldArrIndex] = oldArr[oldArrIndex];
	}
	/**
	 * Adds a PQAble to the array and Sets its index
	 * @param p 
	 * @param index
	 */
	public void add(PQAble p, int index){
		//check if the array needs to expand
		if(p!=null) p.setIndex(index);
		doubleAndCopy(index);
		if(index >= oldArrIndex){
			arr[index] = p;
		}else{
			oldArr[index] = p;
		}
		//Copy over from the old array to the new one
		copyFromOld();
	}
	/**
	 * Gets the object at specified index
	 * @param index The index of the object we are getting
	 * @return The object at index i
	 */
	public PQAble get(int index){
		if(index >= arr.length) return null;
		if(index >= oldArrIndex){
			return arr[index];
		}else{
			return oldArr[index];
		}
	}
	
	public int getLength(){
		return arr.length;
	}
}
